package com.cxg.fairy.ec.main.cart;

import android.content.Context;
import android.graphics.Color;
import android.graphics.Paint;
import android.support.v7.widget.AppCompatImageView;
import android.support.v7.widget.AppCompatTextView;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutCompat;
import android.view.View;
import android.view.inputmethod.InputMethodManager;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.cxg.fairy.app.AccountManager;
import com.cxg.fairy.app.Latte;
import com.cxg.fairy.net.RestClient;
import com.cxg.fairy.net.callback.ISuccess;
import com.cxg.fairy.ui.recycler.MultipleFields;
import com.cxg.fairy.ui.recycler.MultipleItemEntity;
import com.cxg.fairy.ui.recycler.MultipleRecyclerAdapter;
import com.cxg.fairy.ui.recycler.MultipleViewHolder;
import com.cxg.fairy.util.log.LatteLogger;
import com.cxg.fairy.util.toasty.Toasty;
import com.diabin.latte.ec.R;
import com.joanzapata.iconify.widget.IconTextView;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.WeakHashMap;


/**
 * Created by CFairy
 */

public final class SignleShopCartAdapter extends MultipleRecyclerAdapter {

    //默认选择状态
    private boolean mIsSelectedAll = false;
    //全选反选模式
    private boolean mDoSelectedAll = false;
    //编辑状态
    private boolean mIsEditable = false;

    private SignleShopCartDelegate delegate = null;

    public SignleShopCartDelegate getDelegate() {
        return delegate;
    }

    public void setDelegate(SignleShopCartDelegate delegate) {
        this.delegate = delegate;
    }

    String oPrice = Latte.getApplicationContext().getResources().getString(R.string.shop_cart_save_tag);

    AppCompatTextView payButton = null;
    AppCompatTextView mTvTotalPrice = null;

    public AppCompatTextView getmTvTotalPrice() {
        return mTvTotalPrice;
    }

    public AppCompatTextView getmTvFreightPrice() {
        return mTvFreightPrice;
    }

    AppCompatTextView mTvFreightPrice = null;

    public void setmTvTotalPrice(AppCompatTextView mTvTotalPrice) {
        this.mTvTotalPrice = mTvTotalPrice;
    }

    public void setmTvFreightPrice(AppCompatTextView mTvFreightPrice) {
        this.mTvFreightPrice = mTvFreightPrice;
    }

    private ICartItemListener mCartItemListener = null;
    private double mTotalPrice = 0.00;

    DecimalFormat format = new DecimalFormat("0.00");
    private WeakHashMap itemTotalPriceMap = new WeakHashMap();
    private String UUID = AccountManager.getSignUUID();

    private static final RequestOptions OPTIONS = new RequestOptions()
            .diskCacheStrategy(DiskCacheStrategy.ALL)
            .centerCrop()
            .dontAnimate();

    SignleShopCartAdapter(List<MultipleItemEntity> data) {
        super(data);
        //初始化总价
        for (MultipleItemEntity entity : data) {
            final double defaultPrice = entity.getField(ShopCartItemFields.DEFAULT_PRICE);
            final int count = entity.getField(ShopCartItemFields.COUNT);
            final double total = defaultPrice * count;
            mTotalPrice = mTotalPrice + total;
        }
        //添加购物测item布局
        addItemType(ShopCartItemType.SHOP_CART_ITEM, R.layout.item_shop_cart);
        addItemType(ShopCartItemType.SHOP_CART_MIGHT_LIKE_TAG, R.layout.item_cart_might_like);
        addItemType(ShopCartItemType.SHOP_CART_MIGHT_LIKE_GOODS, R.layout.item_cart_might_like_goods);
    }

    public void setIsSelectedAll(boolean isSelectedAll) {
        this.mIsSelectedAll = isSelectedAll;
    }

    public void setDoSelectedAll(boolean doSelectedAll) {
        this.mDoSelectedAll = doSelectedAll;
    }

    public void setIsEditable(boolean isEditable) {
        this.mIsEditable = isEditable;
    }

    public void setCartItemListener(ICartItemListener listener) {
        this.mCartItemListener = listener;
    }

    public double getTotalPrice() {
        return mTotalPrice;
    }

    @Override
    protected void convert(final MultipleViewHolder holder, final MultipleItemEntity entity) {
        super.convert(holder, entity);

        //先取出所有值
        final int id = entity.getField(MultipleFields.ID);
        final String thumb = entity.getField(MultipleFields.IMAGE_URL);
        final String title = entity.getField(ShopCartItemFields.TITLE);
        final String desc = entity.getField(ShopCartItemFields.DESC);
        final int count = entity.getField(ShopCartItemFields.COUNT);
        final String price = entity.getField(ShopCartItemFields.PRICE);
        final double defaultPrice = entity.getField(ShopCartItemFields.DEFAULT_PRICE);
        final double promotionPrice = entity.getField(ShopCartItemFields.PROMOTION_PRICE);
        final boolean promotionStatus = entity.getField(ShopCartItemFields.PROMOTION_STATUS);
        final int promotionLimitQuantity = entity.getField(ShopCartItemFields.PROMOTION_LIMIT);
        final String unit = entity.getField(ShopCartItemFields.UNIT);
        final String goodsName = entity.getField(ShopCartItemFields.GOODS_NAME);
        final String text = entity.getField(ShopCartItemFields.TEXT);
        final boolean status = entity.getField(ShopCartItemFields.STATUS);

        final boolean selected = entity.getField(ShopCartItemFields.IS_SELECTED);

        //取出所以控件
        final AppCompatImageView imgThumb = holder.getView(R.id.image_item_shop_cart);
        final AppCompatTextView tvTitle = holder.getView(R.id.tv_item_shop_cart_title);
        final AppCompatTextView tvDesc = holder.getView(R.id.tv_item_shop_cart_desc);
        final AppCompatTextView tvPrice = holder.getView(R.id.tv_item_shop_cart_price);
        final AppCompatTextView tvCount = holder.getView(R.id.tv_item_shop_cart_count);
        final IconTextView iconIsSelected = holder.getView(R.id.icon_item_shop_cart);
        final MyNumberButton numberButton = holder.getView(R.id.number_button);

        final LinearLayoutCompat iconIsSelectedLL = holder.getView(R.id.icon_item_shop_cart_ll);


        final AppCompatTextView tvLikeTag = holder.getView(R.id.tv_shopcart_mightlike_tag);

        final AppCompatImageView ivSuggestImg = holder.getView(R.id.iv_cart_suggest_item_img);
        final AppCompatTextView tvSuggestName = holder.getView(R.id.tv_cart_suggest_item_name);
        final AppCompatTextView tvSuggestUnit = holder.getView(R.id.tv_cart_suggest_item_unit);
        final AppCompatTextView tvSuggestPrice = holder.getView(R.id.tv_cart_suggest_item_price);
        final AppCompatTextView tvSuggestDefaultPrice = holder.getView(R.id.tv_item_shop_cart_default_price);
        final AppCompatTextView tvSuggestPromoteDesc = holder.getView(R.id.tv_item_shop_cart_promotion_desc);
        final LinearLayoutCompat llItemCartLikeGoods = holder.getView(R.id.ll_cart_like_goods);

        switch (holder.getItemViewType()) {
            case ShopCartItemType.SHOP_CART_ITEM:

                //赋值
                tvTitle.setText(title);
                tvDesc.setText(unit);

                if (promotionStatus) {
                    tvSuggestDefaultPrice.setText("¥"+defaultPrice);
                    tvSuggestDefaultPrice.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
                    tvPrice.setText("¥"+format.format(promotionPrice));
                    tvSuggestPromoteDesc.setText("(每个ID限购"+promotionLimitQuantity+"件,超出按原价计算)");
                } else {
                    tvPrice.setText("¥"+format.format(defaultPrice));
                    tvSuggestDefaultPrice.setVisibility(View.INVISIBLE);
                    tvSuggestPromoteDesc.setVisibility(View.INVISIBLE);
                }

                tvCount.setText(String.valueOf(count));

                Glide.with(mContext)
                        .load(thumb)
                        .apply(OPTIONS)
                        .into(imgThumb);

                numberButton.setBuyMax(100)
                        .setInventory(100)
                        .setCurrentNumber(count)
                        .setOnWarnListener(new MyNumberButton.OnWarnListener() {
                            @Override
                            public void onWarningForInventory(int inventory) {
                                Toasty.error(mContext, "当前库存:" + inventory).show();
                            }

                            @Override
                            public void onWarningForBuyMax(int buyMax) {
                                Toasty.error(mContext, "超过最大购买数量:" + buyMax).show();
                            }

                            /**
                             * 加减器交互
                             */
                            @Override
                            public void onCountItemAmount() {
                                final int skuId = entity.getField(MultipleFields.ID);
                                mTvTotalPrice = (AppCompatTextView) holder.itemView.getRootView().findViewById(R.id.tv_shop_cart_total_price);
                                mTvFreightPrice = (AppCompatTextView) holder.itemView.getRootView().findViewById(R.id.tv_shop_cart_other_price);
                                payButton = (AppCompatTextView) holder.itemView.getRootView().findViewById(R.id.tv_shop_cart_pay);
                                RestClient.builder()
                                        .url("shop_cart_number_button")
                                        .loader(mContext)
                                        .params("uuid",UUID)
                                        .params("skuId", skuId)
                                        .params("count",numberButton.getNumber())
                                        .success(new ISuccess() {
                                            @Override
                                            public void onSuccess(String response) {
                                                //请求刷新视图
                                                delegate.updateRecycleView(response);
                                                delegate.checkItemCount();
                                                delegate.initIconSelectAll();
                                                delegate.setPayButton();
                                                notifyDataSetChanged();
                                                //更新结算按钮
                                                setPayButton(payButton);
                                            }
                                        })
                                        .build()
                                        .post();
                            }
                        });

                //隐藏软键盘
                InputMethodManager imm = (InputMethodManager) holder.itemView.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(holder.itemView.getRootView().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);

                //初始化数据
                entity.setField(ShopCartItemFields.IS_SELECTED, selected);

                if (mDoSelectedAll) {
                    //勾选模式
                    entity.setField(ShopCartItemFields.IS_SELECTED, mIsSelectedAll);
                }

                //重新获取状态
                final boolean isSelected = entity.getField(ShopCartItemFields.IS_SELECTED);
                //根据数据状态显示左侧勾勾
                if (isSelected) {
                    //iconIsSelected.setTextColor(ContextCompat.getColor(Latte.getApplicationContext(), R.color.app_main));
                    iconIsSelected.setText("{icon-cart-circle-check-fullyes #FF0000}");
                } else {
                    //iconIsSelected.setTextColor(Color.GRAY);
                    iconIsSelected.setText("{icon-cart-circle-check-no}");
                }

//                LatteLogger.e("itemStaus:",""+mIsEditable+"  | mDoSelectedAll="+mDoSelectedAll+"   | isSelected="+isSelected);


                /**
                 * 左侧单选点击事件
                 */
                iconIsSelectedLL.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        final boolean currentSelected = entity.getField(ShopCartItemFields.IS_SELECTED);
                        final int skuId = entity.getField(MultipleFields.ID);
                        payButton = (AppCompatTextView) holder.itemView.getRootView().findViewById(R.id.tv_shop_cart_pay);
                        mTvTotalPrice = (AppCompatTextView) holder.itemView.getRootView().findViewById(R.id.tv_shop_cart_total_price);
                        mTvFreightPrice = (AppCompatTextView) holder.itemView.getRootView().findViewById(R.id.tv_shop_cart_other_price);
                        LatteLogger.e("UUID=",UUID);
                        LatteLogger.e("skuid=",skuId+"");
                        LatteLogger.e("isSelected=",isSelected+"");
                        RestClient.builder()
                                .url("shop_cart_single_select")
                                .loader(mContext)
                                .params("uuid", UUID)
                                .params("skuId", skuId)
                                .params("isSelected",!currentSelected)
                                .success(new ISuccess() {
                                    @Override
                                    public void onSuccess(String response) {
                                        //刷新勾选状态
                                        if (currentSelected) {
                                            iconIsSelected.setText("{icon-cart-circle-check-no}");
                                            entity.setField(ShopCartItemFields.IS_SELECTED, false);
                                        } else {
                                            iconIsSelected.setText("{icon-cart-circle-check-fullyes #FF0000}");
                                            entity.setField(ShopCartItemFields.IS_SELECTED, true);
                                        }
                                        //请求刷新视图
                                        delegate.updateRecycleView(response);
                                        delegate.checkItemCount();
                                        delegate.initIconSelectAll();
                                        delegate.setPayButton();
                                        notifyDataSetChanged();
                                        //更新全选icon状态
                                        updateIconSelectAll(holder);
                                        setPayButton(payButton);
                                    }
                                })
                                .build()
                                .post();
                    }
                });

                break;

            case ShopCartItemType.SHOP_CART_MIGHT_LIKE_TAG:
                //tvLikeTag.setText(text);
                break;
            case ShopCartItemType.SHOP_CART_MIGHT_LIKE_GOODS:
                tvSuggestUnit.setText(unit);
                tvSuggestPrice.setText(price);
                tvSuggestName.setText(goodsName);
                Glide.with(mContext)
                        .load(thumb)
                        .apply(OPTIONS)
                        .into(ivSuggestImg);
                break;
            default:
                break;
        }
    }

    @Override
    public int getSpanSize(GridLayoutManager gridLayoutManager, int position) {
        return getData().get(position).getField(ShopCartItemFields.SPAN_SIZE);
    }

    @Override
    public int getItemCount() {
        return super.getItemCount();
    }

    public int getSelectedItemCount() {
        int itemCount = 0;
        for (MultipleItemEntity entity : mData) {
            if (entity.getField(ShopCartItemFields.IS_SELECTED)) {
                itemCount++;
            }
        }
        return itemCount;
    }

    public String getSelectedItemIds() {
        StringBuffer sb = new StringBuffer();
        for (MultipleItemEntity entity : mData) {
            if (entity.getField(ShopCartItemFields.IS_SELECTED)) {
                int skuId = entity.getField(MultipleFields.ID);
                sb.append(",").append(skuId);
            }
        }
        return sb.deleteCharAt(0).toString();
    }

    public int getCartItemCount() {
        int cartItemCount = 0;
        for (MultipleItemEntity entity : mData
                ) {
            if (entity.getItemType() == 46) {
                cartItemCount++;
            }
        }
        return cartItemCount;
    }

    public void setPayButton(AppCompatTextView payButton) {
        if (getSelectedItemCount() == 0) {
            payButton.setEnabled(false);
            payButton.setBackgroundColor(Color.GRAY);
            payButton.setText("去结算");
        } else {
            payButton.setEnabled(true);
            payButton.setBackgroundColor(Color.RED);
            payButton.setText("去结算(" + getSelectedItemCount() + ")");
        }
    }

    //动态更新视图
    public void updateRecyclerView(String response,MultipleViewHolder holder) {
        mData.clear();
        ShopCartDataConverter sdc = new ShopCartDataConverter();
        ArrayList<MultipleItemEntity> datas = sdc.setJsonData(response).convert();
        Float amount = sdc.getAmount();
        Float freight = sdc.getFreight();
        mData.addAll(datas);

        //合计
        mTvTotalPrice = this.getmTvTotalPrice();
        mTvTotalPrice.setText(String.format("%.2f", amount));

        AppCompatTextView mTvTotalPrices = (AppCompatTextView) holder.itemView.getRootView().findViewById(R.id.tv_shop_cart_total_price);
        mTvTotalPrices.setText(String.format("%.2f", amount));


        //运费
        this.getmTvFreightPrice().setText(String.format(oPrice, freight+""));
    }

    //单选操作下 同步 全选按钮状态
    public void updateIconSelectAll(final MultipleViewHolder holder) {
        IconTextView mIconSelectAll = (IconTextView) holder.itemView.getRootView().findViewById(R.id.icon_shop_cart_select_all);
        if (getCartItemCount() == getSelectedItemCount()) {
            updateIconStatus(holder,true);
        } else {
            updateIconStatus(holder,false);
        }
    }

    //更新选中
    public void updateIconStatus(final MultipleViewHolder holder,boolean status) {
        IconTextView mIconSelectAll = (IconTextView) holder.itemView.getRootView().findViewById(R.id.icon_shop_cart_select_all);
        if (status) {
            mIconSelectAll.setText("{icon-cart-circle-check-fullyes #FF0000}");
            mIconSelectAll.setTag(1);
            setIsSelectedAll(true);
        } else {
            mIconSelectAll.setText("{icon-cart-circle-check-no}");
            mIconSelectAll.setTag(0);
            setIsSelectedAll(false);
        }
    }

}
